package com.aaa.zuul.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;

/**
 * @author: Bug Maker
 * @date: 2021/2/16 19:12
 * @description:
 */
public class JWTUtils {
    public static final String TOKEN="tokenSING";

    /**
     * 创建token
     * @param day 过期时间（按天）
     * @param map 载荷信息
     * @return token
     */
    public static String initToken(Integer day, Map<String,String> map){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,day);
        JWTCreator.Builder builder = JWT.create();
        //创建jwt builder
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String, String> item : entries) {
            builder.withClaim(item.getKey(),item.getValue());
        }
        //设置过期时间和签名
        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(TOKEN));
    }

    /**
     * 验证token
     * @param token token字符串
     * @return t=正确，f=错误
     */
    public static Boolean verifyToken(String token){
        try {
            JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
            return true;
        }catch (Exception e){

            return false;
        }
    }

    /**
     * 获取荷载信息
     * @param token token字符串
     * @return DecodedJWT
     */
    public static DecodedJWT getTokenPayload(String token){
        if(verifyToken(token)){
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
            return jwtVerifier.verify(token);
        }else {
            return null;
        }
    }
}
